from tools import *
import json
import urllib2
import os
from tools import BASEURL
from tools import UUID
import urllib

LOG = getlogger(__name__)
command_addr = os.path.join(url, 'command')


def notify_job_status(name, method, signature, result=None, err=None):
    try:
        addr = os.path.join(command_addr, UUID, name)
        data = {}
        if result:
            data['result'] = result
        if err:
            data['error'] = err
        if signature:
            data['signature'] = signature
        data['method'] = method
        param = urllib.urlencode(data)
        f = urllib2.urlopen(addr, param)
        code = f.getcode()
        if code != 200:
            raise Exception('HTTP COEE:%d' % code)
        result = json.loads(f.read())
        if method == 'fetch':
            return result['signature']
    except Exception, ex:
        LOG.error('error while notify job:[%s] method: [%s], %s',
                  (name, method, ex))


notify_result = lambda result, job: notify_job_status(job.name, 'finish', None, result, None)
notify_err = lambda err, job: notify_job_status(job.name, 'finish', None, None, err)
CALLBACKS['notify_result'] = notify_result
ERR_CALLBACKS['notify_err'] = notify_err


def main(url=BASEURL, uid=None):
    if uid is None:
        uid = UUID
    addr = os.path.join(command_addr, uid)
    f = urllib2.urlopen(addr)
    code = f.getcode()
    result = []
    if code != 200:
        raise Exception('HTTP COEE:%d' % code)
    for name, value in json.loads(f.read()).items():
        data = json.loads(value['content'])
        signature = notify_job_status(None, name, 'fetch')
        result.append((name, data, signature))
        LOG.error('gennerate new job: %s', name)
    return result
